<template>
  <div class="teacher-set">
    <el-form :model="form" label-width="80px">
      <el-form-item label="头像">
        <div class="avatar-wrapper" @mouseenter="showCamera = true" @mouseleave="showCamera = false">
          <img v-if="form.avatar" :src="form.avatar" :style="{ width: '100px', height: '100px', borderRadius: '50%' }" />
          <el-icon v-if="showCamera" class="camera-icon" size="20" @click="openUploadDialog">
            <upload-filled />
          </el-icon>
          <div v-else class="default-avatar">+</div>
        </div>
      </el-form-item>
      <el-form-item label="姓名">
        <el-input v-model="form.realname" disabled></el-input>
      </el-form-item>

      <div class="double-column">
        <div class="form-row">
          <el-form-item label="手机号">
            <el-input v-model="form.phone" disabled></el-input>
          </el-form-item>
          <el-form-item label="学号">
            <el-input v-model="form.studentId" disabled></el-input>
          </el-form-item>
        </div>
      </div>
      <div class="form-row">
        <el-form-item label="性别" style="width: 48%">
          <el-select v-model="form.gender">
            <el-option label="男" value="male"></el-option>
            <el-option label="女" value="female"></el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="生日" style="width: 48%">
          <el-date-picker v-model="form.birthday" type="date"></el-date-picker>
        </el-form-item>
      </div>
      <el-form-item label="学校">
        <el-input v-model="form.school"></el-input>
      </el-form-item>
      <el-form-item label="昵称">
        <el-input v-model="form.nickname"></el-input>
      </el-form-item>
       <el-form-item label="个签">
        <el-input
          v-model="form.signature"
          type="textarea"
          :maxlength="300"
          show-word-limit
          :autosize="{ minRows: 3 }"
        ></el-input>
      </el-form-item>

      <el-form-item label="修改密码">
    <template v-if="!isChangePwd">
      <el-button type="text" @click="isChangePwd = true">●</el-button>
    </template>
    <template v-else>
      <div v-if="!isVerifyPwd" class="password-step">
        <div class="input-with-actions">
          <el-input
            v-model="form.currentPassword"
            placeholder="请输入当前密码"
            type="password"
            style="flex:1;margin-right:10px"
          ></el-input>
          <div class="action-buttons">
            <el-button type="text" @click="verifyCurrentPassword">验证</el-button>
            <el-button type="text" style="color:gray"  @click="isChangePwd = false">取消</el-button>
          </div>
        </div>
      </div>

      <!-- 第二步：设置新密码 -->
      <div v-else class="password-step">
        <el-input
          v-model="form.newPassword"
          placeholder="请输入新密码"
          type="password"
          style="margin-bottom: 18px"
        ></el-input>
        <el-input
          v-model="form.confirmNewPassword"
          placeholder="请确认新密码"
          type="password"
          style="margin-bottom: 18px"
        ></el-input>
      </div>
    </template>
  </el-form-item>
     <el-form-item>
  <el-button
    type="primary"
    @click="handleSubmit"
    :disabled="isChangePwd && !isVerifyPwd"
  >保存</el-button>
  <el-button type="text" style="color:gray" @click="cancelForm">取消</el-button>
</el-form-item>
    </el-form>
    <!-- 头像上传裁剪对话框 -->
    <el-dialog v-model="uploadDialogVisible" title="上传头像">
  <div class="upload-container">
    <el-upload
      :show-file-list="false"
      :auto-upload="false"
      @change="handleFileChange"
      :before-upload="beforeUpload">
      <template #trigger>
        <el-button type="primary">选择图片</el-button>
      </template>
    </el-upload>

    <div class="cropper-container">
      <img
        v-if="cropperImage"
        id="cropperImage"
        :src="cropperImage"
      >
      <div v-else class="upload-placeholder">
        <el-icon :size="60"><upload-filled /></el-icon>
        <p>请上传图片</p>
      </div>
    </div>

    <el-button
      v-if="cropperImage"
      type="primary"
      @click="handleCropEnd"
      style="display: block; margin: 0 auto;"
    >确认裁剪</el-button>
  </div>
</el-dialog>
  </div>
</template>

<script>
import { ref,nextTick } from 'vue'
import { UploadFilled } from '@element-plus/icons-vue'
import { ElMessage } from 'element-plus'
import Cropper from 'cropperjs'
import 'cropperjs/dist/cropper.css'
import { onMounted } from 'vue'
import { getUserInfo, updateUserInfo, uploadAvatar } from '@/services/user'

export default {
  name: 'TeacherSet',
  components: {
    UploadFilled
  },
  setup() {
    const userId =  ref(localStorage.getItem('id'));
     const form = ref({
      avatar: '',
      nickname: '',
      signature: '',
      gender: '',
      birthday: '',
      school: '',
      currentPassword: '',
      newPassword: '',
      confirmNewPassword: '',
      realname: '',
      phone: '',
      studentId: ''
    })
    const showCamera = ref(false)
    const uploadDialogVisible = ref(false)
    const cropperImage = ref('')
    const isChangePwd = ref(false)
    const cropperInstance = ref(null)
    const isVerifyPwd = ref(false)


  // 验证当前密码
  const verifyCurrentPassword = () => {
    if (!form.value.currentPassword) {
      ElMessage.error('请输入当前密码')
      return
    }
    // 这里可以添加实际验证逻辑
    isVerifyPwd.value = true
    ElMessage.success('验证通过')
  }
 const initData = async () => {
      try {
        const res = await getUserInfo(userId.value)
        const data = res.data.data
        form.value = {
          avatar: data.img_url,
          nickname: data.nickname,
          signature: data.user_intro,
          gender: data.gender === '男' ? 'male' : 'female',
          birthday: data.birthday,
          school: data.university_name,
          realname: data.username,
          phone: data.phone_num,
          studentId: data.stu_number,
          // 保持其他字段不变
          currentPassword: '',
          newPassword: '',
          confirmNewPassword: ''
        }
      } catch (error) {
        ElMessage.error('数据加载失败')
      }
    }

    const handleSubmit = async () => {
      try {
        // 构造请求数据
         const requestData = {
            id: userId.value,
            nickname: form.value.nickname,
            user_intro: form.value.signature,
            gender: form.value.gender === 'male' ? '男' : '女',
            university_name: form.value.school,
            img_url: form.value.avatar,  // 添加头像字段
            phone_num: form.value.phone,
            stu_number: form.value.studentId
          };

        if (isChangePwd.value) {
          // 密码修改逻辑
          if (!form.value.currentPassword || !form.value.newPassword) {
            ElMessage.error('请填写完整密码信息')
            return
          }
          requestData.password = form.value.newPassword
        }

        await updateUserInfo(userId.value, requestData)
        ElMessage.success('保存成功')
        isChangePwd.value = false
        isVerifyPwd.value = false
      } catch (error) {
        ElMessage.error('保存失败：' + error.message)
      }
    }
      onMounted(() => {
      initData()
    })
    // 打开头像上传对话框
    const openUploadDialog = () => {
      uploadDialogVisible.value = true
    }

    // 上传前处理，限制文件类型和大小
    const beforeUpload = (file) => {
  // 允许的文件类型
  const allowedTypes = ['image/jpeg', 'image/png', 'image/webp']
  // 最大文件大小 2MB
  const maxSize = 2 * 1024 * 1024

  // 校验文件类型
  if (!allowedTypes.includes(file.type)) {
    ElMessage.error('仅支持 JPG/PNG/WEBP 格式的图片')
    return false
  }

  // 校验文件大小
  if (file.size > maxSize) {
    ElMessage.error(`文件大小不能超过 ${maxSize/1024/1024}MB`)
    return false
  }

  return true
}

    // 上传成功处理
    const handleUploadSuccess = (response, file) => {
      cropperImage.value = URL.createObjectURL(file.raw)
      nextTick(() => {
        if(cropperInstance.value) {
          cropperInstance.value.destroy()
        }
const image = document.getElementById('cropperImage')
console.log('Cropper constructor:', Cropper) // 调试用
console.log('Image element:', image) // 调试用
cropperInstance.value = new Cropper(image, {
  aspectRatio: 1,
  viewMode: 1
})
      })
    }

    const handleFileChange = (file) => {
      if (!file) return
        if (!beforeUpload(file.raw)) { // 添加前置校验
          cropperImage.value = '' // 清空裁剪区域
          return
        }
      const reader = new FileReader()
      reader.onload = (e) => {
        cropperImage.value = e.target.result
        nextTick(() => {
          if(cropperInstance.value) {
            cropperInstance.value.destroy()
          }
          const image = document.getElementById('cropperImage')
          cropperInstance.value = new Cropper(image, {
            aspectRatio: 1,
            viewMode: 1
          })
        })
      }
      reader.readAsDataURL(file.raw)
    }




    // 裁剪结束处理
const handleCropEnd = async () => {
  try {
    const canvas = cropperInstance.value.getCroppedCanvas();
    canvas.toBlob(async (blob) => {
      // 将blob转换为File对象
      const file = new File([blob], 'avatar.jpg', {
        type: 'image/jpeg',
        lastModified: Date.now()
      });

      const res = await uploadAvatar(file);
        await updateUserInfo(userId.value, {
        id: userId.value,  // 添加id字段
        img_url: res.data.data
      });

      // 根据接口响应结构调整赋值
      localStorage.setItem('userAvatar', res.data.data);
      form.value.avatar = res.data.data;
      ElMessage.success('头像更新成功');
      uploadDialogVisible.value = false;
    }, 'image/jpeg', 0.9);
  } catch (error) {
    ElMessage.error('头像更新失败：' + error.message);
  }
}

    // 保存表单
    const saveForm = () => {
      // 这里可以添加实际保存数据到后端的逻辑，比如使用axios
      ElMessage.success('保存成功')
    }

    // 取消表单
    const cancelForm = () => {
      // 可以添加重置表单等逻辑
      ElMessage.info('操作取消')
    }

    // 修改密码
    const changePassword = () => {
      if (form.value.newPassword!== form.value.confirmNewPassword) {
        ElMessage.error('新密码和确认新密码不一致')
        return
      }
      // 这里可以添加实际修改密码到后端的逻辑，比如使用axios
      ElMessage.success('密码修改成功')
      isChangePwd.value = false
    }

    return {
      form,
      showCamera,
      uploadDialogVisible,
      cropperImage,
      isChangePwd,
      openUploadDialog,
      beforeUpload,
      handleUploadSuccess,
      handleCropEnd,
      saveForm,
      cancelForm,
      changePassword,
      handleFileChange,
         isVerifyPwd,
    verifyCurrentPassword,
    handleSubmit
    }
  }
}
</script>

<style scoped>
.password-step {
  width: 800px;
}
.action-buttons {
  display: flex;
  align-items: center;
  gap: 20px;
}
.teacher-set {
  padding: 20px;
}
.avatar-wrapper {
  position: relative;
  display: inline-block;
  width: 100px;
  height: 100px;
  border-radius: 50%;
  overflow: hidden;
}
.default-avatar {
  width: 100%;
  height: 100%;
  background-color: #ccc;
  display: flex;
  justify-content: center;
  align-items: center;
  font-size: 24px;
  color: white;
}

.form-row {
  display: flex;
  justify-content: space-between;
  width: 700px;
  margin-bottom: 18px; /* 与原表单间距保持一致 */
}
.form-row .el-form-item {
  margin-bottom: 0; /* 去除默认底部间距 */
}

.el-input {
  width: 700px;  /* 统一输入框宽度 */
}

.el-select {
  width: 700px;
}

.el-date-picker {
  width: 700px;
}

.el-input.is-disabled {
  width: 400px;
}
.el-input.is-disabled :deep(.el-input__inner) {
  background-color: #f5f7fa;
  color: #c0c4cc;
  cursor: not-allowed;
}
:deep(.el-form-iStudentSettem__content) {
  width: 700px;
}

:deep(.el-input),
:deep(.el-select),
:deep(.el-date-editor) {
  width: 100% !important;
}
.el-input.is-disabled {
  width: 100%;
}

/* 修正手机号/学号布局 */
.form-row {
  width: 850px;
}
.form-row .el-form-item {
  width: 48%;
}
.el-textarea {
  width: 800px;
}
.el-textarea :deep(.el-input__count) {
  background: rgba(255, 255, 255, 0.8);
  padding-right: 5px;
}
.camera-icon {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  background: rgba(0, 0, 0, 0.5);
  border-radius: 50%;
  padding: 8px;
  color: white;
  cursor: pointer;
  transition: opacity 0.3s;
  opacity: 0;
}
.avatar-wrapper:hover .camera-icon {
  opacity: 1;
}

/* 调整上传对话框样式 */
::v-deep .el-dialog {
  width: 600px;
}

.cropper-container {
  width: 560px;
  height: 400px;
  margin: 20px auto;
  position: relative;
}

#cropperImage {
  max-width: 100%;
  max-height: 100%;
  object-fit: contain;
}

.input-with-actions {
  display: flex;
  align-items: center;
  width: 100%;
}

.action-buttons {
  display: flex;
  align-items: center;
  height: 40px; /* 与输入框高度保持一致 */
}
</style>
